'use strict';

//导入模板引擎模块
let nunjucks = require('nunjucks');

//包装模板引擎
function createEnv(path,opts){
    path = path || 'views';
    opts = opts || {};
    //可选功能
    let envOptions = {
        autoescape:opts.autoescape === undefined? true:opts.autoescape,   //自动转义
        throwOnUndefined:opts.throwOnUndefined === undefined?false:opts.throwOnUndefined,   //抛出异常
        watch: opts.watch === undefined ? false : opts.watch,    // 模板改变时，页面是否重新加载（默认为false）
        noCache: opts.noCache === undefined ? false : opts.noCache   //是否有缓存
    }
    let env = nunjucks.configure(path,envOptions);
    return env;
}

//暴露出去
module.exports = async (ctx,next) => {
    //为ctx绑定render方法
    ctx.render = function(view,model){
        //调用函数
        let env = createEnv('views');
        //渲染数据返回网页
        ctx.response.body = env.render(view,model);
    } 
    //执行下一个异步函数
    await next();
}
